import { createVNode, render } from 'vue'
import Toast from '../components/Toast.vue'

export function showToast(message, type = 'info', duration = 2000) {
  // 为每次调用创建独立容器，确保组件重新挂载并触发进入动画
  const container = document.createElement('div')
  document.body.appendChild(container)

  const vnode = createVNode(Toast, { message, type, duration })
  render(vnode, container)

  // 在持续时间结束后，延时销毁（预留过渡动画时间）
  const total = Math.max(0, Number(duration) || 2000) + 300
  setTimeout(() => {
    render(null, container)
    if (container.parentNode) container.parentNode.removeChild(container)
  }, total)
}

export const toast = {
  info: (msg, duration) => showToast(msg, 'info', duration),
  success: (msg, duration) => showToast(msg, 'success', duration),
  error: (msg, duration) => showToast(msg, 'error', duration),
  warn: (msg, duration) => showToast(msg, 'warn', duration)
}
